* Create connected when excluding patients treated by the same cardiologist previously (used to create columns 3 and 4 of App Table A4 and Figure A6)

use "$savedata/ami_analysis_mainspef.dta", clear

drop if derv_age<35

merge m:1 extract using "$savedata/no_past_interactions.dta"
keep if _merge==3
keep if match==0


egen hosp_vol_year = sum(ami), by(trust_code finyear)

* Have to treat at least 100 heart attack patients in a year to be included in the data
keep if hosp_vol_year>99

egen vol = sum(ami), by(pconsult)
egen vol_trust = sum(ami), by(pconsult trust_code)

drop if vol_trust<10

egen vol_year = sum(ami), by(pconsult finyear)

egen vol_trust_year = sum(ami), by(pconsult trust_code finyear)


* Make restrictions by minimum volumes of consultant-trust pairs

foreach x in 10 25 50 100{
	
preserve
* Only want to be linked by docs who treat x or more patients in a given hospital
collapse (sum) ami, by(trust_code pconsult)

keep if ami>=`x'

egen constotal = sum(ami), by(pconsult)
rename ami trust_constotal

* Connect using doctors work in at least 2 hospitals; with a minimum volume in total

* Number of hospitals worked in a given year
bys pconsult: gen x=_n
egen total_trusts_worked_in = max(x), by(pconsult)

* Keep only the connectors (those in more than one hospital in a given year)
keep if total_trusts>1

* Now keep only those who do a minimum of 10 or more
keep if trust_constotal>`x'

* for graphs, want to plot these
egen mincheck = min(trust_constotal), by(pconsult)
egen maxcheck = max(trust_constotal), by(pconsult)

* This is the original connected set

gen akm_set_mainspef`x'_nomatch = 1
gen akm_connectors`x'_nomatch = 1
egen akm_connecting_pats`x'_nomatch = sum(trust_constotal), by(trust_code)

collapse (max) akm_set_mainspef`x' (sum) akm_connectors`x' akm_connecting_pats`x', by(trust_code)

save "$savedata/connect_total`x'_noprevmatch.dta", replace
count

restore
}
